package com.liu.voluntary.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liu.voluntary.mapper.ActivityMapper;
import com.liu.voluntary.mapper.OrderMapper;
import com.liu.voluntary.pojo.Activity;
import com.liu.voluntary.pojo.Order;
import com.liu.voluntary.pojo.User;
import com.liu.voluntary.service.ActivityService;
import com.liu.voluntary.service.OrderService;
import com.liu.voluntary.util.CookieUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CookieValue;
import sun.security.krb5.internal.Ticket;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ActivityService activityService;
    @Resource
    private RedisTemplate redisTemplate;


    @Override
    @Transactional
    public Order seckill(@CookieValue("Ticket") String Ticket, HttpServletRequest request, HttpServletResponse response, Activity activity) {

//        User user = (User) request.getSession().getAttribute(userTicket);
        User user = (User) redisTemplate.opsForValue().get("user:" + Ticket);

//        QueryWrapper<Order> wrapper = new QueryWrapper<>();
//        wrapper.eq("activity_id",activity.getId());
//        Order order = orderService.getOne(wrapper);

        //库存减一   不具备原子性
//        seckillGoods.setStockCount(seckillGoods.getStockCount()-1);
//        seckillGoodsService.updateById(seckillGoods);

        UpdateWrapper<Activity> wrapper2 = new UpdateWrapper<>();
        wrapper2.setSql("number = number - 1")
                .eq("id", activity.getId())
                .gt("number", 0);   //大于0


        boolean update = activityService.update(wrapper2);


        if (!update) {
            return null;
        }

        //生成普通订单
        Order order = new Order();
        order.setActivityId(activity.getId());
        order.setActivityName(activity.getActivityName());
        order.setUserMobile(user.getMobile());
        order.setUserId(user.getId());


        orderMapper.insert(order);

        return order;
    }

}
